package com.sixbro.authorization.util;

import com.sixbro.authorization.security.domain.OAuth2UserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * <p>
 *
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021/6/15 14:00
 */
public class SpringSecurityHolder {
    public static final String ANY_ANONYMOUS_USER = "anyAnonymousUser";

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                .filter(Authentication::isAuthenticated)
                .orElse(null);
    }

    public static String currentUsername() {
        return Optional.ofNullable(getAuthentication())
                .map(Authentication::getName)
                .orElse(ANY_ANONYMOUS_USER);
    }

    public static OAuth2UserDetails getUser(){
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }

    /**
     * 获取当前用户
     * @param authentication 认证信息
     * @return 当前用户
     */
    private static OAuth2UserDetails getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof String) {
            new OAuth2UserDetails(0L, "18922206218", "10000",(String) principal, "N/A", AuthorityUtils.NO_AUTHORITIES);
        }else if(principal instanceof OAuth2UserDetails){
            return (OAuth2UserDetails) principal;
        }
        return null;
    }
}
